package lolxxs.chenyanting.aop;

import lolxxs.chenyanting.cache.Cache;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

//@Component
//@Aspect
//@Slf4j
public class CacheableAspect {
//    @Autowired
    private Cache cache;

    @Pointcut("@annotation(cuit.tangwangzheng.annotation.Cacheable)")
    public void pointcut() {

    }

    @Before(value = "pointcut()")
    public void before(JoinPoint joinPoint) {
//        try {
//            printTree(joinPoint);
//        } catch (InvocationTargetException e) {
//            e.printStackTrace();
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }

        //            org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint
//            getId 0
//            getSignature Result cuit.tangwangzheng.controller.UserController.login(User)
//            getTarget cuit.tangwangzheng.controller.UserController@2d74cbbd
//            getArgs [Ljava.lang.Object;@47299eab
//            getKind method-execution
//            getSourceLocation org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint$SourceLocationImpl@24e4f1dd
//            getThis cuit.tangwangzheng.controller.UserController@2d74cbbd
//            getStaticPart execution(Result cuit.tangwangzheng.controller.UserController.login(User))
//            getClass class org.springframework.aop.aspectj.MethodInvocationProceedingJoinPoint

        Signature signature = joinPoint.getSignature();
        Class declaringType = signature.getDeclaringType();
        signature.getName();
        Method[] methods = declaringType.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(signature.getName())) {
                try {
                    Object invoke = method.invoke(joinPoint.getTarget(), joinPoint.getArgs());
                    System.out.println("执行结果"+invoke);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
//        System.out.println("Arrays.toString(joinPoint.getArgs()) "+Arrays.toString(joinPoint.getArgs()));
    }

    public void printTree(Object object) throws InvocationTargetException, IllegalAccessException {
        Class<?> aClass = object.getClass();
        System.out.println(aClass.getName());
        Method[] methods = aClass.getMethods();
        for (Method method : methods) {
            if (method.getName().startsWith("get")) {
                Object invoke = method.invoke(object);
                System.out.println(method.getName()+" "+invoke);
            }
        }
    }

}
